package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysMenuDao sysMenuDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("===doGetAuthorizationInfo===");
        SysUser user= (SysUser) principalCollection.getPrimaryPrincipal();
        Set<String> set=sysMenuDao.selectUserPermissions(user.getId());
        System.out.println("set.permissions="+set);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username= upToken.getUsername();

        SysUser sysUser = sysUserDao.selectUserByUsername(username);
        if(sysUser==null) throw new UnknownAccountException();
        if(sysUser.getValid()==0)throw new LockedAccountException();

        ByteSource credentialsSalt=ByteSource.Util.bytes(sysUser.getSalt());

        SimpleAuthenticationInfo info= new SimpleAuthenticationInfo(
                sysUser,sysUser.getPassword(),credentialsSalt,this.getName());
        return info;
    }
    @Override
    public CredentialsMatcher getCredentialsMatcher(){
        HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1);
        return matcher;
    }

}
